<template>
  <div>排期页面</div>

  <Banner :film-id="curFilmId" :film-list="films" @change="onFilmChange" />

  <DateList :cur-date="curDate" :list="curFilm?.showDate" @change="onDateChange" />

  <ScheduleList :list="schedules" />
</template>

<script lang="ts" setup name="schedule">
import { getCinemaFilmList } from '@/api'
import Banner from './components/banner.vue'
import DateList from './components/date-list.vue'
import ScheduleList from './components/schedule-list.vue'
import { useScheduleStore } from '@/stores/schedule'

const route = useRoute()
const router = useRouter()
const scheduleStore = useScheduleStore()

// id - 影院Id
// filmId - 电影Id
// date - 排期日期
const { id, filmId, date } = route.params

// 电影列表
const films = ref<IFilm[]>([])
// 排期列表
const schedules = ref<ISchedule[]>([])
// 当前选择的电影Id
//    初始值：是 url 地址中的 filmId 参数的值
const curFilmId = ref<number>(filmId ? +filmId : -1)
// 当前选择的日期
//    初始值：是 url 地址中的 date 参数的值
const curDate = ref<number>(date ? +date : -1)
// 挡墙选择的电影
const curFilm = computed(() => films.value.find((item) => item.filmId === curFilmId.value))

// 电影选择发生变化
async function onFilmChange(film: IFilm) {
  // 1. 更新 curFilmId, curDate
  curFilmId.value = film.filmId
  curDate.value = film.showDate?.[0] as number

  // 2. 获取排期接口
  // const { schedules: list } = await getScheduleList(+id, film.filmId, film.showDate?.[0] as number)
  const list = await scheduleStore.fetchScheduleList(+id, film.filmId, film.showDate?.[0] as number)

  // 3. 赋值
  schedules.value = list

  // 修改url地址
  router.replace({ name: 'schedule', params: { id, filmId: film.filmId, date } })
}

// 日期选择发生变化
async function onDateChange(date: number) {
  // 1. 更新 curDate
  curDate.value = date

  // 2. 获取排期接口
  const list = await scheduleStore.fetchScheduleList(+id, curFilmId.value, date)

  // 3. 赋值
  schedules.value = list

  // 修改url地址
  router.replace({ name: 'schedule', params: { id, filmId: curFilmId.value, date } })
}

async function refresh() {
  // 获取电影列表数据
  const { films: list } = await getCinemaFilmList(+id)
  films.value = list

  if (curFilmId.value === -1) {
    // 当 curFilmId 为 -1 时，使用电影列表中第一条数据作为它的Id
    curFilmId.value = list[0].filmId
  }
  if (curDate.value === -1) {
    curDate.value = list[0].showDate?.[0] as number
  }

  // 获取排期列表数据
  // await getScheduleList(+id, curFilmId.value, curDate.value)
  const sList = await scheduleStore.fetchScheduleList(+id, curFilmId.value, curDate.value)
  schedules.value = sList
}

refresh()
</script>
